// utils/tocGenerator.js
import  { Editor } from "tinymce";

export interface TocItem {
  level:number;
  title:string;
  anchor:string;// 锚点
}

class TOCGenerator {
    // 从编辑器内容生成TOC
    // static generateFromEditor(editor:Editor) {
    //     const contents = editor.getContent();
    //     return this.generateFromDelta(contents);
    // }

    // 从Delta格式生成TOC
    // static generateFromDelta(delta:any) {
    //     const tocItems:TocItem[] = [];
        
    //     delta.ops.forEach(op => {
    //         if (op.attributes && op.attributes.header) {
    //             const level = op.attributes.header;
    //             const title = op.insert;
    //             const anchor = this.generateAnchor(title);
                
    //             tocItems.push({
    //                 level: level,
    //                 title: title,
    //                 anchor: anchor
    //             });
    //         }
    //     });
        
    //     return tocItems;
    // }

    // 从HTML内容生成TOC（备用方案）
    static generateFromHTML(html:string) { 
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');
        const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
        const tocItems:TocItem[] = [];
        headings.forEach(heading => {
            const level = parseInt(heading.tagName.substring(1));
            const title = heading.textContent;
            const anchor = heading.id || this.generateAnchor(title);
            
            // 确保标题有ID
            if (!heading.id) {
                heading.id = anchor;
            }
            
            tocItems.push({
                level: level,
                title: title,
                anchor: anchor
            });
        });
        
        return tocItems;
    }

    // 生成锚点ID
    static generateAnchor(title:string) {
        return title.toLowerCase()
            .replace(/[^\w\u4e00-\u9fa5]+/g, '-')
            .replace(/^-+|-+$/g, '');
    }
}

export default TOCGenerator;